#!/bin/bash

set -e

if [ $# -lt 1 ]; then
   echo "$0 <opengrok tar ball> [opengrok root directory]"
   exit 1
fi

TARBALL=$1
GROK_ROOT=${2:-$PWD/opengrok}

echo "Creating opengrok directories ..."
mkdir -pv ${GROK_ROOT}/{src,data,dist,etc,log}

echo "Untar opengrok tar ball ..."
tar -C ${GROK_ROOT}/dist --strip-components=1 -xf ${TARBALL}

echo "Coping log configuration file ..."
cp -v ${GROK_ROOT}/dist/doc/logging.properties ${GROK_ROOT}/etc

echo "Setup management tools (python) ..."
cd ${GROK_ROOT}/dist/tools
python3 -m venv env
. ./env/bin/activate
pip install opengrok-tools.tar.gz

echo "Delopy source.war ..."
export PATH=${GROK_ROOT}/dist/tools/env/bin:$PATH
read -p "Please input web app path:" app_dir

sudo ${GROK_ROOT}/dist/tools/env/bin/opengrok-deploy -c ${GROK_ROOT}/etc/configuration.xml ${GROK_ROOT}/dist/lib/source.war "${app_dir}"

sudo chown hitmoon:hitmoon ${GROK_ROOT} -R
read -p "Install Universtal ctags, Press any key to continue ..."

echo "Now you can put code under ${GROK_ROOT}/src and use opengrok-update-index.sh to index for the first time"
echo "After that, you can use update_index_per_project.sh to index per project"
echo "Finally, (optionaly) use opengrok.service to start web service ;-)"


